<?php
/**
 * Created by PhpStorm.
 *
 * @Date: 2017-08-02
 * @Time: 17:04
 * @Author: cdkay
 * @Email: network@iyuanma.net
 *
 * @File： Live.php
 */
namespace app\admin\model\live;

use app\api\model\live\Live;
use app\api\model\LiveToken;
use app\common\lib\rongcloud\RongCloud;
use app\common\model\teacher\Teacher;
use app\common\utils\DateTimeUtil;
use think\Db;
use think\db\Query;
use think\Model;

/**
 * Class LiveChannel
 * @package app\admin\model\live
 *
 * @property integer id
 * @property string cid
 * @property string name
 * @property string summary
 * @property integer teacher_id
 * @property integer status
 * @property string announcement
 * @property string last_play_at
 * @property string chat_room_id
 * @property integer number_online
 * @property integer online_num
 * @property string pushurl
 * @property string pullurlhttp
 * @property string pullurlhls
 * @property string pullurlrtmp
 *
 * @property Teacher teacher
 * @property Live live
 * @property Live[] lives
 */
class LiveChannel extends Model {
    protected $table = 'live_channel';
    protected $pk = 'id';

    const STATUS_IDLE           = 0;
    const STATUS_LIVE           = 1;
    const STATUS_DISABLE        = 2;

    const STATUS_MAP_NET_EASE = [
        0   => self::STATUS_IDLE,
        1   => self::STATUS_LIVE,
        2   => self::STATUS_DISABLE,
        3   => self::STATUS_LIVE,
    ];
    public static $StatusNames = [
        self::STATUS_IDLE           => '空闲',
        self::STATUS_LIVE           => '直播',
        self::STATUS_DISABLE        => '禁用',
    ];

    public static function getByCID($cid) {
        return self::get(['cid' => $cid]);
    }

    /**
     * 检查频道是否使用过
     *
     * @param $id
     * @return bool
     */
    public static function check_used($id) {

        $sql = <<<SQL
SELECT exists(SELECT * FROM live WHERE live_channel_id=:id LIMIT 1) AS re
SQL;
        $re = Db::query($sql, ['id' => $id]);

        return $re[0]['re'] ?? false;
    }

    public static function listNames($teacherId = -1,$year='') {
        $condition = [];
        if ($teacherId != -1) {
            $params['c.teacher_id'] = $teacherId;
        }
        if($year){
            $condition['date_part(\'year\',c.last_play_at)']=$year;
        }
        $list=self::alias('c')->join('teacher t','t.id=c.teacher_id','left')->field('c.id,c.name,c.teacher_id,c.pushurl,c.pullurlrtmp,c.pullurlhls,t.realname teacher_name')
            ->where($condition)->order('c.id DESC')->select();
        return $list;
    }

    /**
     * @param int $page
     * @param int $rows
     * @param int $status
     * @param int $uid
     * @return false|static[]
     */
    public static function apiList($page = 1, $rows = 3, $status = -1, $uid = 0,$official=1) {
        $condition['status']=$status != -1 ? $status : ['in',[static::STATUS_IDLE,static::STATUS_LIVE]];
        $list = self::alias('c')
            ->join('teacher t','c.teacher_id=t.id','LEFT')
            ->field('c.id,c.name,c.teacher_id,c.number_online,c.status,c.chat_room_id,c.online_num')
            ->where(function ($q) use ($condition,$official){
                $q->where($condition);
                if($official){
                    $q->where('c.official','=',$official);
                }
            })
            ->order('c.status','desc')
            ->paginate($rows,false,['page'=>$page])
            ->toArray();
        foreach ($list['data'] as $k=>$item) {
            // $number_online = $item['number_online']>0?($item['number_online']+$item['online_num']):$item['number_online'];
            $list['data'][$k]['number_online']=countDataNum($item['number_online'], $item['online_num'], true); // 假数据，😄
            unset($list['data'][$k]['online_num']);

            $live = Live::get(function (Query $query) use ($item, $uid) {
                $query->alias('l')->join('teacher t','t.id=l.teacher_id');
                $query->field("l.id,l.title,l.cover,l.teacher_id,l.status,l.live_date,l.start_time,l.end_time,l.num_liked,l.live_price,l.playback_price,l.bind_curriculum_id, 
                t.realname teacher_name,t.avatar teacher_avatar, 
                exists(select 1 from user_live_buy ulb where ulb.live_id=l.id and uid=$uid) live_has_bought,
                exists(select 1 from user_live_subscribe uls where uls.live_id=l.id and userid=$uid) has_subscribed,
                exists(select 1 from user_buy_curriculum ubc where ubc.uc_curriculum=l.bind_curriculum_id and ubc.uc_user=$uid) curriculum_has_bought");
                $query->where('live_channel_id',$item['id']);
                $query->whereIn('status', [Live::STATUS_START,Live::STATUS_END,Live::STATUS_RECORD,]);
                $query->order('CASE status WHEN 1 THEN 1 WHEN 3 THEN 2 WHEN 2 THEN 3 END');
                $query->order('id','desc');
            });
            if ($live) {
                $live->fixProperty();
                $list['data'][$k]['live'] = $live;
            } else {
                $list['data'][$k]['live'] = new \stdClass();
            }
        }
        return $list;
    }

    public static function apiDetail($id, $uid,$token='') {

        $model = self::get(function (Query $query) use ($id) {
            $query->where('id',$id);
            $query->field('id,name,summary,teacher_id,status,pullurlhls,pullurlrtmp,chat_room_id,announcement,number_online,online_num');
        });
        if (empty($model)) return null;

        $model->share_url = self::shareUrl($model->id);
        // $model->number_online = Live::liveViewNumber($model->number_online); // 假数据，😄
        // $number_online = $model->number_online>0?($model->number_online+$model->online_num):$model->number_online;
        $model->number_online = countDataNum($model->number_online, $model->online_num, true); // 假数据，😄
        unset($model->online_num);

        $lives = Live::all(function (Query $query)use ($model, $uid) {
            $query->alias('l');
            $query->join('teacher t','t.id=l.teacher_id');
            $query->join('curriculum c','c.curriculum_id=l.bind_curriculum_id','LEFT');
            $query->where('l.live_channel_id', $model->id);
            $query->where('l.live_date', date('Y-m-d'));
            $query->field("l.id,l.title,l.cover,l.status,l.teacher_id,l.live_date,l.start_time,l.end_time,l.live_price,l.playback_price,l.bind_curriculum_id, 
            t.realname teacher_name,t.avatar teacher_avatar, c.curriculum_name,
            exists(select 1 from user_live_subscribe uls where uls.live_id=l.id and uls.userid=$uid) has_subscribed,
            exists(select 1 from user_live_buy ulb where ulb.live_id=l.id and uid=$uid) live_has_bought,
            exists(select 1 from user_buy_curriculum ubc where ubc.uc_curriculum=l.bind_curriculum_id and ubc.uc_user=$uid) curriculum_has_bought");
            $query->order('l.start_time');
        });
        foreach ($lives as $live) {
            if (Live::STATUS_START == $live->status) {
                if ($model->teacher_id <= 0) $model->teacher_id = $live->teacher_id;
            }
            $live->fixProperty();
        }


        $model->lives = $lives;
        $model->current_live = Live::get(function (Query $query) use ($model, $uid) {
            $query->alias('l');
            $query->join('teacher t','t.id=l.teacher_id');
            $query->join('curriculum c','c.curriculum_id=l.bind_curriculum_id','LEFT');
            $query->where('l.live_channel_id', $model->id);
            $query->whereIn('l.status',[Live::STATUS_START, Live::STATUS_RECORD]);
            $query->field("l.id,l.title,l.cover,l.status,l.teacher_id,l.live_date,l.start_time,l.end_time,l.live_price,l.playback_price,l.bind_curriculum_id,l.is_encrypt, 
            t.realname teacher_name,t.avatar teacher_avatar, c.curriculum_name,
            exists(select 1 from user_live_subscribe uls where uls.live_id=l.id and uls.userid=$uid) has_subscribed,
            exists(select 1 from user_live_buy ulb where ulb.live_id=l.id and uid=$uid) live_has_bought,
            exists(select 1 from user_buy_curriculum ubc where ubc.uc_curriculum=l.bind_curriculum_id and ubc.uc_user=$uid) curriculum_has_bought");
            $query->order('l.id','desc');
            $query->order('l.status','asc');
        });
        if ($model->current_live) $model->current_live->fixProperty();

        if($model->current_live->is_encrypt){
            if($token){
                $liveToken=LiveToken::getOne($token);
                if($liveToken){
                    $model->current_live->is_encrypt=false;
                }else{
                    $model->pullurlrtmp='';
                    $model->pullurlhls='';
                }
            }else{
                $model->pullurlrtmp='';
                $model->pullurlhls='';
            }

        }
        if ($model->teacher_id > 0) {
            $teacher = Teacher::get(function (Query $query)use ($model, $uid) {
                $query->where('t.id', $model->teacher_id);
                $query->alias('t');
                $query->join('teacher_degree d','d.id=t.degree_id');
                $query->field("t.id,t.realname,t.avatar,t.num_followed,t.followed as set_followed,t.intro, 
                d.name as degree, exists(select 1 from user_follow_teacher uft where uft.teacher_id=t.id and uft.userid=$uid) followed");
            });

            $teacher->followed = false;
            if ($teacher && $uid>0) $teacher->followed = Teacher::checkFollow($model->teacher_id, $uid);

            // 老师文章总数统计
            $articleCount = Db::table('teacher_essay')->where('teacher_id', $model->teacher_id)->where('hide', 'false')->count();
            $teacher['article_total'] = $articleCount;

            // 老师课程视频总数统计
            $courseCount = Db::table('curriculum_video')->where('video_teacher', $model->teacher_id)->where('hide', 'false')->count();
            $teacher['course_total'] = $courseCount;

            // 老师问答总数统计
            $askCount = Db::table('ask')->where('ask_teacher', $model->teacher_id)->count();
            $teacher['ask_total'] = $askCount;

            $teacher['num_followed'] = countDataNum($teacher['num_followed'], $teacher['set_followed']);
            unset($teacher['set_followed']);

            $model->teacher = $teacher;
        } else {
            // 获取当前直播间的最后一条直播节目数据
            $liveLast = Db::table('live')->where('live_channel_id', $id)->where('status', 1)->order('id desc')->find();
            if (!$liveLast) $liveLast = Db::table('live')->where('live_channel_id', $id)->where('status', 'in', [1, 3])->order('id desc')->find();

            $teacher = Teacher::get(function (Query $query)use ($liveLast, $uid) {
                $query->where('t.id', $liveLast['teacher_id']);
                $query->alias('t');
                $query->join('teacher_degree d','d.id=t.degree_id');
                $query->field("t.id,t.realname,t.avatar,t.num_followed,t.followed as set_followed,t.intro, 
                d.name as degree, exists(select 1 from user_follow_teacher uft where uft.teacher_id=t.id and uft.userid=$uid) followed");
            });

            $teacher->followed = false;
            if ($teacher && $uid>0) $teacher->followed = Teacher::checkFollow($liveLast['teacher_id'], $uid);

            // 老师文章总数统计
            $articleCount = Db::table('teacher_essay')->where('teacher_id', $liveLast['teacher_id'])->where('hide', 'false')->count();
            $teacher['article_total'] = $articleCount;

            // 老师课程视频总数统计
            $courseCount = Db::table('curriculum_video')->where('video_teacher', $liveLast['teacher_id'])->where('hide', 'false')->count();
            $teacher['course_total'] = $courseCount;

            // 老师问答总数统计
            $askCount = Db::table('ask')->where('ask_teacher', $liveLast['teacher_id'])->count();
            $teacher['ask_total'] = $askCount;

            $teacher['num_followed'] = countDataNum($teacher['num_followed'], $teacher['set_followed']);
            unset($teacher['set_followed']);

            $model->teacher = $teacher;
            // $model->teacher = new \stdClass();
        }

        return $model;
    }

    public static function shareUrl($id) {
        return sprintf('%s/live/liveRoom/%d',config('server.wapHost'), $id);
    }

    public static function getTeacher($teacherId = 0) {

    }
}
